package com.lb.bigdata.spark.p1;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

public class JavaLambdaWordCountOps {
    public static void main(String[] args) {
        //Logger.getLogger("org.apache.spark").setLevel(Level.ERROR);
        SparkConf conf = new SparkConf();
        conf.setMaster("local[*]");
        conf.setAppName("JavaLambdaWordCount");
        JavaSparkContext jsc = new JavaSparkContext(conf);

        JavaRDD<String> linesRDD = jsc.textFile("D:/a.txt");

        JavaRDD<String> wordsRDD = linesRDD.flatMap(line -> Arrays.asList(line.split("\\s+")).iterator());

        JavaPairRDD<String, Integer> pairRDD = wordsRDD.mapToPair(word -> new Tuple2<String, Integer>(word, 1));

        JavaPairRDD<String, Integer> ret = pairRDD.reduceByKey((v1, v2) -> v1 + v2);

        ret.foreach(kv -> System.out.println("(" + kv._1 + ", " + kv._2 + ")"));
    }
}
